package com.rhb.rhbaiagent.controller;

import com.rhb.rhbaiagent.App.LoveApp;
import com.rhb.rhbaiagent.agent.RhbManus;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private LoveApp loveApp;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ChatModel dashscopeChatModel;

    @GetMapping("/love_app/chat/sync")
    public String doChatWithLoveAppSync(String message, String chatId) {
        return loveApp.dochat(message, chatId);
    }

    @GetMapping(value = "/love_app/chat/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> doChatWithLoveAppSSE(String message, String chatId){
        return loveApp.doChatWithToolsByStream(message, chatId);
    }

    @GetMapping("/love_app/chat/sse/SseEmiter")
    public SseEmitter doChatWithLoveAppSseEmitter(String message, String chatId){
        SseEmitter sseEmitter = new SseEmitter(180000L);
        loveApp.doChatWithToolsByStream(message,chatId)
                .subscribe(
                        chunk -> {
                            try{
                                sseEmitter.send(chunk);
                            }catch (IOException e){
                                sseEmitter.completeWithError(e);
                            }
                        }, sseEmitter::completeWithError, sseEmitter::complete
                );
        return sseEmitter;
    }

    @GetMapping("/manus/chat")
    public SseEmitter doChatWithManus(String message){
        RhbManus rhbManus = new RhbManus(allTools, dashscopeChatModel);
        return rhbManus.runStream(message);
    }

}
